package com.xyd.servlet;

import com.xyd.entity.Product;
import com.xyd.service.impl.ProductServiceImpl;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/ProductGetServlet")
public class ProductGetServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Long id = Long.parseLong(request.getParameter("id"));
    ProductServiceImpl productService = new ProductServiceImpl();
    Product product1 = productService.getProductByEpid1(id);
    request.setAttribute("product", product1);
    HttpSession session = request.getSession();

    String name = "";
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie c : cookies
      ) {
        if (c.getName().equals("listCookie")) {
          name = c.getValue();
        }
      }
    }
    name += request.getParameter("id") + ",";
    String[] arr = name.split(",");
    if (arr != null && arr.length > 0) {
      if (arr.length > 1000) {
        name = "";
      }
    }
    Cookie myCookie = new Cookie("listCookie", name);
    List<Product> list = productService.getOldProduct(name);
    session.setAttribute("mylist", list);
    response.addCookie(myCookie);
    request.getRequestDispatcher("product-view.jsp").forward(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    doGet(req, resp);
  }
}
